<?php
namespace Wap \ Controller;
use Think \ Controller;
use Wap \ Service \ CustomerService;
use Wap \ Service \ SessionService;
use Wap \ Service \ WeixinService;
use Wap \ Service \ PraiseService;
use Common \ Service \ Sms \ ShortMessageService;
use Wap \ Model;

class PraiseItemController extends Controller {

	public function debug() {
		$key = I("get.key", "--", "");
		$debug = S("debug_$key");
		$this->ajaxReturn($debug);
	}

	/**
	 *函数名:items
	 *函数描述:ajax获取作品信息
	 *
	 */
	public function items() { //TODO: thinkphp 分页技术
		$page = I("get.page", 1, ""); //1:默认从第一页开始读取
		$limit = I("get.limit", 10, ""); //默认每页读取10个
		$condition['status'] = I("get.status", 1, ""); //默认读取审核通过的作品
		$condition['praise_id'] = I("get.praise", 0, ""); //

		$result = D('praiseItem')->fetch($condition, $page, $limit);
		$this->ajaxReturn($result);
	}

    public function itemseat() { //TODO: thinkphp 分页技术
        $page = I("get.page", 1, ""); //1:默认从第一页开始读取
        $limit = I("get.limit", 10, ""); //默认每页读取10个
        $condition['status'] = I("get.status", 1, ""); //默认读取审核通过的作品
        $condition['praise_id'] = I("get.praise", 0, ""); //

        $result = D('praiseItem')->fetcheat($condition, $page, $limit);
        $this->ajaxReturn($result);
    }

	/*public function upload()
	{
	    $this->assign( "praise", 6 );
	    $condition['praise_id'] = I( "get.praise", 6, '' );
		$condition['id'] = I( 'get.id', 80, '' );
		$condition['status'] = -1;
	
		// $this->share['link'] = C("SITE_URL").'/'.U('Wap/Praise/index', array( 'praise' => $condition['praise'] ) );
	
		$data = D( 'praise_item' )->where( $condition )->find();
	
		// $this->assign( "share", $this->share );
		$this->assign( "customer", $customer_id );
		$this->assign( "data", $data );
		// $this->display( "upload" );
	    $this->display( "Praise/upload" );
	}*/

	public function students() {
		$page = I('get.page', 1, '');
		$limit = I('get.limit', 10, '');
		$condition['status'] = I('get.status', 1, '');
		$condition['praise_id'] = I('get.praise_id', 6, '');
		$condition['teacher_name'] = I('get.teacher_name', '', '');
		$condition['teacher_telephone'] = I('get.teacher_telephone', '', '');

		$result = D('praiseItem')->fetch($condition, $page, $limit);
		$this->ajaxReturn($result);
	}

	public function search() {
		$condition['praise_id'] = I("post.praise", -1, "");
		$keyword = I("post.keyword", "", "");
		if (eregi('^[0-9]*$', $keyword)) {
			$condition['esm_praise_item.grade'] = intval($keyword);
		} else {
			$condition['show_name'] = array (
				"LIKE",
				"%$keyword%"
			);
		}
		$condition['status'] = 1;

		$data = D("praise_item")->field(array (
			'esm_praise_item.id as id, esm_praise_item.grade as grade, esm_praise_item.pic as pic, esm_praise_item.show_name as show_name, esm_praise_item.votes as votes, esm_praise_item.share as share'
		))->where($condition)->select();
		//->find();
		//$result['size'] = count( $data ) ? 1 : 0;
		//$result['datas'] = array( $data );
		$result['size'] = count($data);
		$result['datas'] = $data;

		$this->ajaxReturn($result);
	}

	public function add() {
		$arr = $_POST;
		foreach ($arr as $key => $value) {
			$arr[$key] = strip_tags($value);
		}
		$id = I('post.id', -1, "");
		$praise_id = I('post.praise_id', -1, ""); //获取活动id
		$customer_id = CustomerService :: getID();
		$praise = PraiseService :: getPraise($praise_id);

		$uid = D('praise_item')->where(array (
			'id' => $id,
			'praise_id' => $praise
		))->getField('uid');

		if ($id <= 0) {
			unset ($arr['id']);
		} else
			if ($uid == null || $customer_id == null || ($customer_id != null && $uid != $customer_id)) { //查看当前用户是否在线
				//return $this->ajaxReturn( array( 'success' => false, 'msg' => '保存失败', 'id' => $id, 'uid' => $praise['uid'], 'customer' => $customer_id, 'praise_id' => $praise['id'] ) );
			}

		trace(array_merge($arr, array (
			'customer_id' => $customer_id
		)), 'praiseitem upload', 'INFO');
		$pattern_img = "/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*(.jpg|.JPG)$/";
		if (isset ($arr['pic']) && !empty ($arr['pic']) && preg_match($pattern_img, $arr['pic']) === 0) {
			$arr['pic'] = C('SITE_URL') . '/' . WeixinService :: downloadImage($arr['pic'], $praise);
		}
		if (isset ($arr['birth_file']) && !empty ($arr['birth_file']) && preg_match($pattern_img, $arr['birth_file']) === 0) {
			$arr['birth_file'] = C('SITE_URL') . '/' . WeixinService :: downloadImage($arr['birth_file'], $praise);
		}
		if (isset ($arr['author_pic']) && !empty ($arr['author_pic']) && preg_match($pattern_img, $arr['author_pic']) === 0) {
			$arr['author_pic'] = C('SITE_URL') . '/' . WeixinService :: downloadImage($arr['author_pic'], $praise);
		}
		if (isset ($arr['teacher_pic']) && !empty ($arr['teacher_pic']) && preg_match($pattern_img, $arr['teacher_pic']) === 0) {
			$arr['teacher_pic'] = C('SITE_URL') . '/' . WeixinService :: downloadImage($arr['teacher_pic'], $praise);
		}
		if (isset ($arr['school_pic']) && !empty ($arr['school_pic']) && preg_match($pattern_img, $arr['school_pic']) === 0) {
			$arr['school_pic'] = C('SITE_URL') . '/' . WeixinService :: downloadImage($arr['school_pic'], $praise);
		}

		$arr['uid'] = $customer_id; //TODO: 上传者ID;
		$arr['add_time'] = time();
		$arr['status'] = 0;
		$arr['praise_id'] = $praise['id'];
		//$arr['praise_id'] = 6;

		//S( "debug_arr", $arr );
		//S( "debug_data", $arr, 3600 );
		// return $this->ajaxReturn( $arr );
		$mode = D("praiseItem");
		// return $this->ajaxReturn( $arr );
		$saved = $mode->insert($arr);
		if ($saved['success'] && isset ($saved['data']) && isset ($saved['data'][0]) /*&& !!$saved['data'][0]['teacher_telephone']*/
			) {
			$sms = new ShortMessageService();
			//$msg = "";
			$msg = sprintf("%s小朋友作品已上传至2015年第四届全国少儿世界和平海报大赛第六赛区作品征集系统。作品编号 %d。", $saved['data'][0]['author_name'], $saved['data'][0]['id']);
			if (!!$saved['data'][0]['teacher_telephone']) {
				//$msg = sprintf("%s小朋友的指导老师，您好！%s已报名参加2015·年第四届全国少儿世界和平海报大赛第六赛区比赛。作品正在审核中。作品投票将于2015年10月28日开始，届时请关注“浙报公益”微信号进入投票页面，搜索作品编号：%d，即可进行投票。", $saved['data'][0]['author_name'], $saved['data'][0]['author_name'], $saved['data'][0]['id']);
				$msg = sprintf("%s小朋友作品已上传至2015年第四届全国少儿世界和平海报大赛第六赛区作品征集系统。作品编号 %d。", $saved['data'][0]['author_name'], $saved['data'][0]['id']);
				$sended = $sms->sendMsgTo($saved['data'][0]['teacher_telephone'], $msg);
				$saved['data'][0]['teacher_telephone'] = $sended ? $saved['data'][0]['teacher_telephone'] : null;
			}
			$telephone = D("customer")->where(array (
				'id' => $saved['data'][0]['uid']
			))->getField("telephone");
			// if( !$telephone ){ $telephone = "18758195480";
			//$msg = sprintf( "您好！%s已成功上传2015第四届全国少儿世界和平海报作品征集活动第六赛区作品。关注“浙报公益”进入投票页面，搜索作品编号：%s，即可进行投票。", $saved['data'][0]['author_name'], $saved['data'][0]['id']);
			$sms->sendMsgTo($telephone, $msg);
		}
		//S( "debug_upload", $saved );
		return $this->ajaxReturn($saved);
	}

	//public function edit()//TODO: just for debug.need to delete
	//{
	//  $id	=	I( "get.id", 102, "" );//TODO: 输入控制
	//	$praise = I( 'get.praise', 18, '' );

	//	$condition['esm_praise_item.id'] = $id;

	//	$datas = D('praiseItem')->fetch_by_id( $id );
	//	$rank = D("praiseItem")->fetch_rank_by_id( $datas['id'] );
	//$check = RuleService::is_good( $praise, $this->user['openid'], array( 'updated_time' => time(), 'praise' => $praise, 'openid' => $this->user['openid'], 'pid' => $id ) );
	//$checked = $check['error'] ? 0 : 1;

	/*if( !count($datas) ){
		$this->error( '该作品不存在、或未被审核通过', '#' );
	}*/

	//$this->assign( "rank", $rank );
	//$this->assign( "result", $datas );
	//$this->assign( 'checked', 1 );
	//$this->display( "Praise/fetch_one" );  //原文件名称 photodetail

	//}

	public function checkCard() {
		$card = I('post.card', "", "");
		$praise = I('post.praise', -1, "");
		$exclude = I('post.exclude', -1, '');

		$result['error'] = 4;
		if (empty ($card)) {
			$result['error'] = 3;
			$this->ajaxReturn($result);
		}
		/*if( preg_match( "/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/", $card ) )
		{
			$result['error'] = 2;
			$this->ajaxReturn( $result );
		}*/

		$condition['card'] = $card;
		$condition['praise_id'] = $praise;
		$condition['id'] = array (
			"not in",
			array (
				$exclude
			)
		);

		$counts = D("praiseItem")->where($condition)->count();
		if ($counts > 0) {
			$result['error'] = 1;
		} else {
			$result['error'] = 0;
		}
		$this->ajaxReturn($result);
	}

	public function rank_teacher() {
		$praise = I("get.praise_id", -1, "");
		$page = I("get.page", 1, "");
		$limit = I("get.praise_id", 10, "");

		$result = D('teacher')->ranks($praise, $page, $limit);
		$this->ajaxReturn($result);
	}
}